<template>
  <div class="title">上传评审结果</div>
  <div v-if="isShowUpload">
    <t-popup
      content="最多只能上传5个文件"
      destroy-on-close
      showArrow
      :visible="showMax && isHovered"
    >
      <div
        class="up-container"
        @mouseenter="isHovered = true"
        @mouseleave="isHovered = false"
        @dragover.prevent  
        @drop="handleDrop"
      >
        <t-upload
          v-if="isShowUpload"
          class="up-container__up"
          v-model="files"
          name="files"
           accept=".pdf,.png,.jpg"
          :auto-upload="true"
          :uploadAllFilesInOneRequest="true"
          :showUploadProgress="true"
          :headers="{ authorization: token }"
          :data="{ assessId: assessId, reportType: '2' }"
          :action="url"
          draggable
          theme="file"
          :multiple="false"
          :sizeLimit="{ size: 10, unit: 'MB', message: '文件大小不能超过10MB' }"
          @fail="handleFail"
          @success="handleSuccess"
          @dragenter="hiddenTx = true"
          @cancel-upload="handleRemove"
          @selectChange="handleSelectChange"
          :before-upload="beforeUpload"
          :disabled="reportFileList?.length === 5"
        >
        </t-upload>
        <div v-if="!hiddenTx" class="up-container__con">
          <icon class="up-container__con--icon" name="plus" />
          <div class="up-container__con--tx">
            Only pdf, png, jpg can be uploaded, and the size does not exceed
            10MB
          </div>
        </div>
      </div>
    </t-popup>
  </div>

  <div class="rp-wrapper">
    <div class="report" v-for="(item, index) in reportFileList" :key="index">
      <div class="report-container">
        <div class="report-container__left">
          <img class="img" src="@/assets/image/report_icon.png" alt="" />
          <div class="con">
            <div class="name">{{ item.fileName }}</div>
            <div class="size">文件大小: {{ item.fileSize }}</div>
            <div class="date">上传日期: {{ item.createTime }}</div>
          </div>
        </div>
      </div>
      <t-popconfirm
        theme="warning"
        content="确定要删除该文件吗?"
        @confirm="delReportCall(item.id)"
      >
        <img v-if="isShowDelete" src="@/assets/image/delete.svg" alt="" />
      </t-popconfirm>
    </div>
  </div>
  <div class="fixed-container" v-if="approvalProcess <= 5">
    <t-space :size="8" class="fixed-container__btn">
      <t-button theme="default" variant="base" @click="goJGLast"
        >上一步</t-button
      >
      <t-button :loading="isLoading" @click="submitForm()">确定</t-button>
    </t-space>
  </div>
</template>
<script setup>
import { Icon } from "tdesign-icons-vue-next";
import { MessagePlugin } from "tdesign-vue-next";
import { getToken, setToken } from "@/utils/auth";
import {
  approvalReportList,
  approvalReportTwoConfirm,
  delReport,
  approvalReportDraftBind,
} from "@/api/sjhg/approval";
import axios from "axios";
import { ref, watch } from "vue";
const props = defineProps({
  assessId: {
    type: Number,
    default: 0,
  },
  approvalProcess: {
    type: Number,
    default: 0,
  },
});
const isHovered = ref(false);
const showMax = ref(false);
const hiddenTx = ref(false);
const isLoading = ref(false);
const isShowUpload = ref(true);
const isShowDelete = ref(true);
const reportFileList = ref([]);
const files = ref([]);
// const url = window.lwConfig.services.auth + '/sjhg/approval/assess/report/draft'
const url = window.lwConfig.services.auth + "/sjhg/multi/upload";
console.log("r = ", url);
const token = "Bearer " + getToken();
console.log("token = ", token);

onMounted(async () => {
  await getReportList();
  console.log("props.approvalProcess = ", props.approvalProcess);
  if (props.approvalProcess != 5) {
    isShowUpload.value = false;
    isShowDelete.value = false;
  }
});
watch(
  () => reportFileList.value?.length,
  (newLength) => {
    showMax.value = newLength === 5;
  }
);
//------------------------------------文件上传失败和成功的回调------------------------
const dragList = ref([])
const handleSelectChange = (files) => {
  dragList.value = files
  if (files.length > 1) {
    // 清空所有选择
    // files.splice(0);
    MessagePlugin.warning(`一次只能上传一个文件`);
    hiddenTx.value = false
    return false;  // 阻止上传
  }else{
    hiddenTx.value = true;
    return true;
  }
};
const allowedTypes = [
        'application/pdf',  // PDF
        'image/png',       // PNG
        // 'image/jpeg',      // JPEG/JPG
        'image/jpg',       // 部分浏览器可能返回 image/jpg
      ];
const handleDrop = (e) => {
  e.preventDefault();
  const files = e.dataTransfer?.files;
  if (!files) return;
  const invalidFiles = Array.from(files).filter(file => 
    !allowedTypes.includes(file.type)
  );
  if (invalidFiles.length > 0) {
    MessagePlugin.warning("只能上传 PDF、PNG、JPG 格式的文件！");
    hiddenTx.value = false
  }
};
const beforeUpload = (file) => {
  if (dragList.value?.length > 1) {
    dragList.value.splice(0)
    return false; // 阻止上传
  } else if(file && !allowedTypes.includes(file.type)){
      MessagePlugin.warning('只能上传 PDF、PNG、JPG 格式的文件！');
      hiddenTx.value = false
      return false;
  }else{
    return true; // 允许上传
  }
};

const handleSuccess = ({ file }) => {
  console.log("response = ", file.response);
  files.value = [];
  hiddenTx.value = false;
  if (file.response.code != 200) {
    MessagePlugin.error(`文件上传失败`);
    return;
  }
  if (file.response.code == 200) {
    // if (file.response.data.code == 200) {
    //   // 调用获取报告列表接口
    //   getReportList()
    // }
    if (file.response.code == 200) {
      bindDraft(file.response?.data);
    }
  }
};

const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};
const handleRemove = (file) => {
  console.log('取消上传的文件：', file);
  hiddenTx.value = false
};
//---------------------------------接口处理------------------------------------

const bindDraft = (data) => {
  var bindData = {};
  bindData.assessId = props.assessId;
  bindData.reportType = 2;
  bindData.fileName = data[0].fileName;
  bindData.fileType = data[0].fileType;
  bindData.fileSize = data[0].fileSize;
  bindData.fileByte = data[0].fileByte;
  bindData.sjhgPath = data[0].sjhgPath;

  approvalReportDraftBind(bindData)
    .then((res) => {
      if (res.code == 200) {
        MessagePlugin.success(res.msg);
        //成功后跳转到下一步
        getReportList();
      } else {
        MessagePlugin.error(res.msg);
      }
    })
    .finally(() => {});
};
//结果
const emit = defineEmits(["goJGLast", "goJGNext"]);
//结果的上一步
const goJGLast = () => {
  emit("goJGLast");
};

const getReportList = async () => {
  var params = {};
  params.assessId = props.assessId;
  params.reportType = 2;
  approvalReportList(params)
    .then((res) => {
      console.log("评审结果返回 = ", res);
      if (res.code == 200) {
        reportFileList.value = res.data || [];
        console.log("reportFileList.value = ", reportFileList.value);
      }
    })
    .finally(() => {});
};

// 上传评审结果
const submitForm = () => {
  if(reportFileList.value?.length < 1){
    MessagePlugin.warning('请上传评审结果');
    return
  }else{
    var params = {};
    params.assessId = props.assessId;
    params.reportType = 1;
    isLoading.value = true;
    approvalReportTwoConfirm(params)
      .then((res) => {
        console.log("评审结果确认返回 = ", res);
        if (res.code == 200) {
          emit("goJGNext");
        }
      })
      .finally(() => {
        isLoading.value = false;
      });
  }
};

const delReportCall = (reportId) => {
  var params = {};
  params.reportId = reportId;
  delReport(params)
    .then((res) => {
      console.log("删除报告返回 = ", res);
      if (res.code == 200) {
        MessagePlugin.success(res.msg);
        getReportList();
      } else {
        MessagePlugin.warning(res.msg);
      }
    })
    .finally(() => {});
};
</script>
<style lang="scss" scoped>
.rp-wrapper {
  margin-bottom: 80px;
  // margin-top: 200px;
}
.up-container {
  z-index: 99;
  cursor: pointer;
  position: relative;
  font-family: PingFang SC-Bold, PingFang SC;
  width: 100%;
  // margin-bottom: 186px;
  &__up {
    // position: absolute;
    width: 100%;
  }
  &__con {
    width: 100%;
    // display: flex;
    // flex-direction: column;
    // justify-content: center;
    // align-items: center;
    text-align: center;
    &--icon {
      position: absolute;
      top: 50px;
      font-size: 22px;
      color: #4e5969;
      margin-top: 6px;
    }
    &--tx {
      position: absolute;
      top: 110px;
      color: #86909c;
      font-size: 12px;
      line-height: 20px;
      width: 100%;
    }
  }
  &:hover {
    :deep(.t-upload__dragger) {
      background: #c9cdd4;
    }
  }
}
:deep(.t-upload__dragger) {
  width: 100%;
  height: 184px;
  border-radius: 4px;
  color: #1d2129;
  font-size: 14px;
  font-family: PingFang SC-Bold, PingFang SC;
  // border: 1px solid #DCDCDC;
  background: #f2f3f5;
  cursor: pointer;
  margin-top: 4px;
}
:deep(.t-upload__dragger-progress-info) {
  flex: 0;
}
:deep(.t-upload__dragger-error) {
  border: 1px dashed #ff4d65;
}
:deep(.t-upload__dragger-progress) {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
:deep(.t-upload__dragger-btns) {
  bottom: 30px;
}
:deep(.t-upload .t-upload__single-name) {
  color: #000000e5;
  font-size: 14px;
  line-height: 22px;
}
:deep(.t-upload__dragger .t-size-s) {
  color: #00000066;
  font-size: 12px;
  line-height: 20px;
}

.fixed-container {
  height: 72px;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 196px;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
  background: #fff;
  box-shadow: 1px 0px 1px 0px rgba(0, 0, 0, 0.25);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  &__btn {
    margin-right: 20px;
  }
}
.report {
  display: flex;
  align-items: center;

  img {
    width: 24px;
    height: 24px;
    margin-left: 12px;
  }
}
.report-container {
  font-family: PingFang SC-Bold, PingFang SC;
  width: 619px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  margin-top: 16px;
  .img {
    width: 90px;
    height: 90px;
  }
  .name {
    font-size: 16px;
    color: #000000e5;
    margin-top: 4px;
  }
  .size {
    margin-top: 12px;
    line-height: 22px;
    color: #00000066;
    font-weight: 400;
    font-size: 14px;
  }
  .date {
    line-height: 22px;
    color: #00000066;
    font-weight: 400;
    font-size: 14px;
    margin-top: 2px;
  }
  .con {
    margin-left: 16px;
  }
  &__left {
    display: flex;
  }
}
.title {
  font-size: 18px;
  color: #252931;
  margin-top: 8px;
  margin-bottom: 16px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;
}
</style>